/*
 * @Author: chenr 526963089@qq.com
 * @Date: 2023-02-16 10:48:01
 * @LastEditors: chenr 526963089@qq.com
 * @LastEditTime: 2023-03-01 14:32:55
 * @FilePath: /library-web/src/router/generatorRouter.ts
 * @Description: 路由树结构拼装 以及获取当前同级路由
 */
import { shallowRef } from 'vue';
import { useRouter } from 'vue-router';
import type { MenusInterface } from '@/api/mock/types';
import type { RouterInterface } from '@/router/types';

/**
 * @description:  根据返回数据创建路由菜单结构
 * @return {*}
 */
export const createMenusRouter = (menus: MenusInterface[], components: any, name: string) => {
  /**
   * @description: 地柜获取数据
   * @param {MenusInterface} routerMap
   * @return {*}
   */

  const generator = function (routerMap: MenusInterface[]) {
    return routerMap.map((item: MenusInterface) => {
      const currentRouter: RouterInterface = {
        path: `/${name}/${item.path}`, //不能重复
        name: `${name}_${item.code}`, // 不能重复  重复导致路由添加失败
        component: shallowRef(components[item.component!]),
        meta: {
          id: item.id,
          pid: item.parentId,
          title: item.name || '',
          icon: item.source || undefined,
        },
      };
      item.children ? (currentRouter.redirect = `/${name}/${item.children[0].path}`) : 'null';
      // 为了防止出现后端返回结果不规范，处理有可能出现拼接出两个 反斜杠
      if (!currentRouter.path.startsWith('http')) {
        currentRouter.path = currentRouter.path.replace('//', '/');
      }
      // 是否有子菜单，并递归处理
      if (item.children && item.children.length > 0) {
        currentRouter.children = generator(item.children);
      }
      return currentRouter;
    });
  };
  return generator(menus);
};

/**
 * @description: 根据当前路由 获取同级路由
 * @param {RouterInterface} addRouters
 * @return {*}
 */
export const getCurrentLevelRouters = (addRouters: RouterInterface[]) => {
  let list: RouterInterface[] = [];
  const router = useRouter();
  const currentRouter = router.currentRoute.value;
  const _get = (routers: RouterInterface[]) => {
    routers.forEach((item) => {
      if (currentRouter.meta?.pid == item.meta?.id) {
        list = [...item?.children!];
      } else {
        _get(item.children || []);
      }
    });
  };
  _get(addRouters || []);
  return list;
};
